package com.sairobo.admin.modules.wechat.service.impl;

import com.google.common.collect.Lists;
import com.sairobo.base.common.constant.SystemConstant;
import com.sairobo.base.common.entity.R;
import com.sairobo.base.common.service.CommonService;
import com.sairobo.base.common.utils.ShiroUtils;
import com.sairobo.base.common.constant.LiveConstant;
import com.sairobo.base.modules.sys.entity.SysRoleEntity;
import com.sairobo.base.modules.sys.entity.SysUserEntity;
import com.sairobo.base.modules.sys.manager.SysUserManager;
import com.sairobo.base.modules.sys.service.SysRoleService;
import com.sairobo.base.modules.sys.service.SysUserService;
import com.sairobo.admin.modules.wechat.service.WeChatService;
import com.sairobo.admin.modules.wechat.weixin.api.Weixin;
import com.sairobo.admin.modules.wechat.weixin.bean.AccessToken;
import com.sairobo.admin.modules.wechat.weixin.bean.User;
import com.sairobo.base.modules.sys.entity.SysUserTokenEntity;
import com.sairobo.base.modules.sys.oauth2.OAuth2Token;
import com.sairobo.admin.modules.wechat.bean.Result;
import com.sairobo.admin.modules.wechat.util.WechatUtil;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信相关~
 *
 * @author admin
 * @email sairobo
 * @url www.sairobo.com
 * @date 2018年1月11日 上午11:01:21
 */
@Service("weChatService")
public class WeChatServiceServiceImpl extends CommonService implements WeChatService {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysUserManager sysUserManager;

    @Override
    public R callBack(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Weixin weixin = new Weixin(WechatUtil.APPID,WechatUtil.APPSECRET);

        //1. 根据取微信回调请求中的code,获取token和openid
        String code = req.getParameter("code");
        Result<AccessToken> tokenResult = weixin.getOAuth2().accessToken(code);
        AccessToken accessToken = tokenResult.getResult();

        //2. 根据获取的token和openid获取微信用户信息
        Result<User> result = weixin.getWeChatUser().snsapiUserInfo(accessToken.getToken(),accessToken.getOpenId());
        User user = result.getResult();
        logger.info("{}-{}登录成功",user.getOpenId(),user.getNickname());

        //3. 先查用户，如果存在直接登录，如果不存在创建用户后登录
        SysUserEntity sysUser = sysUserService.getWechatUserByUnionid(user.getUnionID());
        if(null==sysUser){
            sysUser = new SysUserEntity();
            //创建用户--注册和绑定
            sysUser.setPassword(LiveConstant.WECHAT_PASSWORD);
            sysUser.setUsername(user.getNickname());
            sysUser.setOpenId(user.getOpenId());

//            //去srblive_user 查找后再赋值
//            SrbliveUser srbliveUser = srbliveUserService.getByunionId(user.getUnionID());
//            if (srbliveUser != null) {
//                sysUser.setOpenId(srbliveUser.getOpenid());
//            }else {
//                throw new RuntimeException("请先关注《知心云》公众号再来操作！");
//                //sysUser.setOpenId(user.getOpenId());
//            }

            sysUser.setUnionId(user.getUnionID());
            sysUser.setRemark(LiveConstant.WECHAT_REMARK);
            sysUser.setStatus(1);
            //绑定角色
            SysRoleEntity role = (SysRoleEntity)sysRoleService.getRoleByRoleSign(LiveConstant.WECHAT_ROLE_CODE).get(SystemConstant.DATA_ROWS);
            sysUser.setRoleIdList(Lists.newArrayList(role.getRoleId()));
            sysUserService.saveUser(sysUser);
        }

        String url  = req.getScheme()+"://"+req.getHeader("host")+req.getContextPath(); //请求协议 http 或 https + 服务器+ 工程名

        //4.登录跳转
        SysUserTokenEntity sysToken = sysUserManager.saveUserToken(sysUser.getUserId());
        OAuth2Token token = new OAuth2Token(sysToken.getToken());
        Subject subject = ShiroUtils.getSubject();
        subject.login(token);
        resp.sendRedirect(url+"/index.html?tk="+sysToken.getToken());
        return R.ok().put("token", sysToken.getToken()).put("expire", sysToken.getGmtExpire());
    }
}
